import { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Toast, Grid } from 'antd-mobile'
import { observer } from 'mobx-react-lite' // 引入react和mobx的中间件
import { serverurl } from '../../utils/request'
import { getUserInfoAPI } from '../../api'
import BackImg from '../../assets/images/29.jpg'
import useStore from '../../store'
import './index.scss'

function Profile() {
  // 导出获取用户信息的store
  const { userStore } = useStore()

  const navigate = useNavigate()

  // 用户数据
  // const [userInfo, setUserInfo] = useState({})

  useEffect(() => {
    // loadUserInfo() // 调用获取用户信息的方法
    userStore.loadUserInfo() // 在mobx中引入用户数据
  }, [])

  // 获取用户信息
  // const loadUserInfo = async () => {
  //   const { data: res } = await getUserInfoAPI()
  //   if (res.status !== 200) return false
  //   console.log('用户信息', res)
  //   setUserInfo(res.body)
  // }

  // 退出登录
  const logout = () => {
    localStorage.removeItem('token')
    Toast.show({
      content: '退出成功',
    })
    // 跳转到首页
    navigate('/')
  }

  return (
    <div className="profile">
      <img src={BackImg} className="backImg" alt="" />
      {/* 用户信息 */}
      <div className="userInfo">
        <img
          className="img"
          src={serverurl + userStore.userInfo.avatar}
          alt=""
        />
        <div className="username">{userStore.userInfo.nickname}</div>
        <button className="logout" onClick={logout}>
          退出
        </button>
        <Link className="edit" to="/updateUser">
          编辑个人资料
        </Link>
      </div>

      {/* 个人功能 */}
      <Grid columns={3} gap={8} className="grid">
        <Grid.Item>
          <div className="gridItem" onClick={() => navigate('/favorites')}>
            <i className="iconfont icon-shoucang"></i>
            <span>我的收藏</span>
          </div>
        </Grid.Item>
        <Grid.Item>
          <div className="gridItem">
            <i className="iconfont icon-Home"></i>
            <span>我的出租</span>
          </div>
        </Grid.Item>
        <Grid.Item>
          <div className="gridItem">
            <i className="iconfont icon-shijian"></i>
            <span>看房记录</span>
          </div>
        </Grid.Item>
        <Grid.Item>
          <div className="gridItem">
            <i className="iconfont icon-qianbao_o"></i>
            <span>成为房主</span>
          </div>
        </Grid.Item>
        <Grid.Item>
          <div className="gridItem">
            <i className="iconfont icon-user"></i>
            <span>个人资料</span>
          </div>
        </Grid.Item>
        <Grid.Item>
          <div className="gridItem">
            <i className="iconfont icon-kefu"></i>
            <span>联系我们</span>
          </div>
        </Grid.Item>
      </Grid>
    </div>
  )
}

// 在使用mobx的地方，包裹一下
export default observer(Profile)
